package org.kongqian.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.kongqian.basic.config.RegisterNoticeRabbitmqConfig;
import org.kongqian.basic.constants.WxConstants;
import org.kongqian.basic.utils.AjaxResult;
import org.kongqian.basic.utils.HttpClientUtils;
import org.kongqian.basic.utils.MD5Utils;
import org.kongqian.basic.utils.PageList;
import org.kongqian.user.domain.Logininfo;
import org.kongqian.user.domain.Wxuser;
import org.kongqian.user.dto.LoginAccountDTO;
import org.kongqian.user.dto.RegisterNoticeDto;
import org.kongqian.user.dto.WechatDTO;
import org.kongqian.user.mapper.LogininfoMapper;
import org.kongqian.user.mapper.WxuserMapper;
import org.kongqian.user.service.ILogininfoService;
import org.kongqian.basic.service.impl.BaseServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kq
 * @since 2022-11-15
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Override
    public AjaxResult loginAccount(LoginAccountDTO dto) {
        String username = dto.getUsername();
        String password = dto.getPassword();
        Integer type = dto.getType();
        //非空校验
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(type) ){
            throw new RuntimeException("登录信息不能为空！");
        }
        //根据用户名去数据库查询数据
        Logininfo logininfo=logininfoMapper.selectLoginByUsername(dto);
        //没有就返回错误信息
        if (Objects.isNull(logininfo)){
            throw new RuntimeException("账号不存在！");
        }
        //有就先判断该账户有没有被禁用
        if (logininfo.getDisable()==0){
            throw new RuntimeException("账号已被停用！");
        }
        //判断密码是否相等
        String salt = logininfo.getSalt();
        password = MD5Utils.encrypByMd5(salt + password);
        if (!password.equals(logininfo.getPassword())){
            throw new RuntimeException("密码错误！");
        }
        //将登录信息存到redis中
        //key 为随机码，将他作为token
        return setLoginInfoAndBack(logininfo);

    }


    @Override
    public AjaxResult wechatLogin(WechatDTO dto) {  //微信登录接口，已和微型进行绑定 直接免密登录
        //参数校验
        String code = dto.getCode();
        if (StringUtils.isEmpty(code)){
            throw new RuntimeException("请获取授权码！");
        }
        //根据code去微信端获取accessToken openid
        String appid = WxConstants.APPID;
        String secret = WxConstants.SECRET;
        String callbackUrl=WxConstants.GET_ACK_URL
                   .replace("CODE", code)
                   .replace("APPID", appid)
                   .replace("SECRET",secret);
        String callbackInfo = HttpClientUtils.httpGet(callbackUrl); //accessToken openid

        //判断是否已绑定微信
        JSONObject jsonObject = JSONObject.parseObject(callbackInfo);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        //根据openid去数据库查
        Wxuser wxuser=wxuserMapper.selectByOpenId(openid);
        //有数据有已经绑定过
        if (Objects.nonNull(wxuser)){
            //有就免密码登录
            //将登陆信息查询出来保存在redis中并返回给前端存在localStorage中，我们要做登录拦截
            Long userId = wxuser.getUserId();
            Logininfo logininfo=logininfoMapper.selectLoginInfoByUserId(userId);
            //返回token  logininfo
            return setLoginInfoAndBack(logininfo);
        }else {
            //没有就跳转到绑定页面
            //返回accessToken openid
            HashMap<String, Object> resultWechatInfo = new HashMap<>();
            resultWechatInfo.put("accessToken", access_token);
            resultWechatInfo.put("openid", openid);
            return AjaxResult.getResult().setSuccess(false).setMessage("goBind").setObject(resultWechatInfo);
        }
    }

    private AjaxResult setLoginInfoAndBack(Logininfo logininfo) {
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token, logininfo,30, TimeUnit.MINUTES);


        //最后返回token 和登录信息
        Map<String,Object> map=new HashMap<>();
        map.put("token", token);
        logininfo.setPassword("");
        logininfo.setSalt("");
        map.put("loginInfo", logininfo);
        return AjaxResult.getResult().setObject(map);
    }
}
